package com.org.litepal.slice.crud;

import com.org.litepal.ResourceTable;
import com.org.litepal.model.Singer;
import com.org.litepal.provider.DataItemProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.text.Font;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.resultset.ResultSet;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import org.litepal.LitePal;
import org.litepal.tablemanager.Connector;

import java.util.ArrayList;
import java.util.List;

public class DeleteSampleAbilitySlice extends AbilitySlice {
    private TextField mSingerIdEdit;

    private TextField mNameToDeleteEdit;

    private TextField mAgeToDeleteEdit;

    private RoundProgressBar mProgressBar;

    private DataItemProvider mAdapter;

    private ArrayList<List<String>> mList = new ArrayList<>();

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_delete_sample);
        mProgressBar = (RoundProgressBar)findComponentById(ResourceTable.Id_progressDelete_bar);
        mSingerIdEdit = (TextField)findComponentById(ResourceTable.Id_delete_id_edit);
        mNameToDeleteEdit = (TextField)findComponentById(ResourceTable.Id_name_to_delete);
        mAgeToDeleteEdit = (TextField)findComponentById(ResourceTable.Id_age_to_delete);


        mAgeToDeleteEdit.setFont(Font.DEFAULT_BOLD);
        Button mDeleteBtn1 = (Button)findComponentById(ResourceTable.Id_delete_btn1);
        Button mDeleteBtn2 = (Button)findComponentById(ResourceTable.Id_delete_btn2);
        ListContainer mDataListView = (ListContainer)findComponentById(ResourceTable.Id_dataDelete_list_view);
        mDeleteBtn1.setClickedListener(component -> {
            try {
                int rowsAffected = LitePal.delete(Singer.class,
                        Long.parseLong(mSingerIdEdit.getText()));
                ToastDialog dialog = new ToastDialog(getContext());
                dialog.setText(String.format("%1$s rows affected.",
                        String.valueOf(rowsAffected)));
                dialog.setDuration(1500);
                dialog.show();
                populateDataFromDB();
            } catch (Exception e) {
                e.printStackTrace();
                ToastDialog dialog = new ToastDialog(getContext());
                dialog.setText("Param is not valid.");
                dialog.setDuration(1500);
                dialog.show();
            }
        });
        mDeleteBtn2.setClickedListener(component -> {
            try {
                int rowsAffected = LitePal.deleteAll(Singer.class, "name=? and age=?",
                        mNameToDeleteEdit.getText(), mAgeToDeleteEdit.getText());
                ToastDialog dialog = new ToastDialog(getContext());
                dialog.setText(String.format("%1$s rows affected.",
                        String.valueOf(rowsAffected)));
                dialog.setDuration(1500);
                dialog.show();
                populateDataFromDB();
            } catch (Exception e) {
                e.printStackTrace();
                ToastDialog dialog = new ToastDialog(getContext());
                dialog.setText("Param is not valid.");
                dialog.setDuration(1500);
                dialog.show();
            }
        });
        mAdapter = new DataItemProvider( mList,getContext());
        mDataListView.setItemProvider(mAdapter);
        populateDataFromDB();
    }
    private void populateDataFromDB() {
        mProgressBar.setVisibility(Component.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                mList.clear();
                List<String> columnList = new ArrayList<>();
                columnList.add("id");
                columnList.add("name");
                columnList.add("age");
                columnList.add("ismale");
                mList.add(columnList);
                ResultSet cursor = null;
                try {
                    cursor = Connector.getDatabase().querySql("select * from singer order by id",
                            null);
                    if (cursor.goToFirstRow()) {
                        do {
                            long id = cursor.getLong(cursor.getColumnIndexForName("id"));
                            String name = cursor.getString(cursor.getColumnIndexForName("name"));
                            int age = cursor.getInt(cursor.getColumnIndexForName("age"));
                            int isMale = cursor.getInt(cursor.getColumnIndexForName("ismale"));
                            List<String> stringList = new ArrayList<>();
                            stringList.add(String.valueOf(id));
                            stringList.add(name);
                            stringList.add(String.valueOf(age));
                            stringList.add(String.valueOf(isMale));
                            mList.add(stringList);
                        } while (cursor.goToNextRow());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                    handler.postTask(() -> {
                        mProgressBar.setVisibility(Component.HIDE);
                        mAdapter.notifyDataChanged();
                    });
                }
            }
        }).start();
    }
    private EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
    @Override
    protected void onStop() {
        super.onStop();
        handler.removeAllEvent();
    }
}